package com.gopay.cashier.web.controller.cloud;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.domain.bean.AcctBean;
import com.gopay.cashier.domain.bean.ExpressCardInfo;
import com.gopay.cashier.domain.bean.LoginUser;
import com.gopay.cashier.domain.bean.PayChannelDtlBean;
import com.gopay.cashier.domain.bean.PayChannelWayBean;
import com.gopay.cashier.web.command.OrderInfo;
import com.gopay.cashier.web.command.PayInfoCommand;
import com.gopay.cashier.web.controller.PayChannelInfoController;
import com.gopay.cashier.web.utils.BisBankBusinessProdConvertUtil;
import com.gopay.cashier.web.utils.CashierConfig;
import com.gopay.cashier.web.utils.PayPwdQuestionsInfo;
import com.gopay.common.constants.YnFlag;
import com.gopay.common.constants.cust.CustPersonInfoConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.OrderFeePayer;
import com.gopay.common.constants.trans.PayChannel;
import com.gopay.common.constants.trans.PayChannelType;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.trans.UserType;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.acps.AcctProd;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.cust.CustPersonInfo;
import com.gopay.common.domain.ep.EpCardBindInfoVo;
import com.gopay.common.domain.gopay.GopayAllCustInfo;
import com.gopay.common.domain.poundage.PoundageRes;
import com.gopay.common.domain.rcs.RcsAntiPhishViolateLog;
import com.gopay.common.exception.GopayException;
import com.gopay.common.rcs.bean.UserDicision;
import com.gopay.common.security.encryptiondecryption.Decrypt;
import com.gopay.common.user.dao.AllCustInfoQueryDAO;
import com.gopay.common.user.manager.DicCustProfessionQueryManager;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.RequestUtils;
import com.gopay.remote.cps.expresspay.EpBankCardRemoteService;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.solution.vo.PayChannelDtlInfo;

/**
 * @author Administrator
 * @CashierController
 */
@Controller
public class CloudPayChannelInfoController extends CloudBaseController {
    protected final static Log logger = LogFactory.getLog(PayChannelInfoController.class);

    private static final String CAS_URL = CashierConfig.get(CashierConfig.CAS_SERVER_URL);
    
    private static final String CASHIER_URL = CashierConfig.get(CashierConfig.CASHIER_URL);
    
    private static final String PORTAL_URL = CashierConfig.get(CashierConfig.PORTAL_URL);
    //是否启用指纹数据采集  0：不启用  1：启用
    private static final String ENABLE_FINGERINFO = CashierConfig.get(CashierConfig.ENABLE_FINGERINFO);


    @Resource(name = "epBankCardService")
    private EpBankCardRemoteService epBankCardService;

    @Resource(name="dicCustProfessionQueryManager")
    private DicCustProfessionQueryManager dicCustProfessionQueryManager;
    
    @Resource(name = "allCustInfoQueryDAO")
    protected AllCustInfoQueryDAO allCustInfoQueryDAO;

    @RequestMapping("/pay/cloud/info.shtml")
    public ModelAndView execute(PayInfoCommand command) throws WebException {
        printRequest();
        
        CpsGenMainOrder order = getMainOrder(getRequest().getParameter("orderId"), true);
        
        CustCorpInfo cust = custCorpInfoService.get(order.getMerId());
        // 校验
        validate(command, order, cust);
        // 防钓鱼
        ModelAndView mav =	 ipCheckDecison(command, order);
        if (null != mav) return mav;
        // 刷新登录用户
        command.setInc(isInchargeOrder(order) ? PayInfoCommand.INCHARGE_ORDER : "n");
        //直连银行；
        if (isDirectBankPay(order)) {
           if(StringUtils.equals(PayChannel._01.value,order.getPayChannel()) || StringUtils.equals(PayChannel._51.value,order.getPayChannel())){
                //个人网银、企业网银-直连模式
                updateDirectBankPayOrder(command, order);
                return directBankPayPage(command);
            }
        }
        return next(order,command);
    }
    
    /**
     * 处理清算方案
     * @param order
     * @param payWay
     */
    private void dealPayChannels(CpsGenMainOrder order,PayChannelWayBean payWay){
        String recvCustId = order.getMainRecvCustId();
        GopayAllCustInfo custInfo=allCustInfoQueryDAO.getAllCustInfoByCustId(recvCustId);
        
        if("1".equals(custInfo.getCustType())){
            //个人客户
            
        }
        else if("2".equals(custInfo.getCustType())){
            //企业客户
            
            //充值
            if(IntTxnCd._00500.value.equals(order.getGopayIntTxnCd())){    
                List<PayChannelDtlBean> pcdList=payWay.getPayChannelList();
                PayChannelDtlBean pcd=null;
                for(PayChannelDtlBean bean : pcdList){
                    if(StringUtils.equals(PayChannelType.OUTSTLM_PAY.value, bean.getPayChannelType())){
                        pcd=bean;
                        break;
                    }
                }
                               
                if(pcd!=null){
                    Map<String, List<PayChannelDtlInfo>> map = pcd.getBankCodes();
                    List<PayChannelDtlInfo> dtlInfoList = map.get(PayChannel._01.value);
                    if(dtlInfoList!=null && dtlInfoList.size()>0){
                        for(int i=0;i<dtlInfoList.size();){
                            if(!dtlInfoList.get(i).getPersonal()){
                                //来自通用方案则排除
                                dtlInfoList.remove(i);                                
                            }else {
                                i++;
                            }
                        }
                        
                    }
                }
            }
            
            
            
        }//else
        
    }
    
    private ModelAndView  next(CpsGenMainOrder order,PayInfoCommand command) throws WebException{
    	HttpServletRequest request = getRequest();
    	String inchargeFlag = command.getInc();
    	String ch = command.getCh();
    	LoginUser loginUser = getLoginUser();
    	ModelAndView mav = new ModelAndView();
    	
        
    	PayChannelWayBean payWay = soluBisPayChannelService.getSoluBisPayChannel(order.getGopayIntTxnCd(), getCloudAcctId(order));
    	
    	//处理清算方案 add by fanghw 20151116
    	dealPayChannels(order,payWay);
    	
    	
    	if(loginUser !=null){
//            PayChannelDtlBean expressBean = payWay.getPayChannelDtl(PayChannelType.CREDIT_EXPRESS_PAY.value);
            PayChannelDtlBean gopayBean = payWay.getPayChannelDtl(PayChannelType.GFB_PAY.value);
            /*if(expressBean!=null && !StringUtils.equals(loginUser.getUser().getUserType(), UserInfoConstants.USER_TYPE_PERSON)){
                //企业用户登录，去掉快捷支付
                payWay.getPayChannelList().remove(expressBean);
                logger.info("corp login remove expresspay channel");
            }*/
            if(gopayBean!=null && IntTxnCd._00100.value.equals(order.getGopayIntTxnCd())){
                payWay.getPayChannelList().remove(gopayBean);
                logger.info("login remove gopay channel");
            }
            
            // 增加校验使用动态口令卡的权限
    		String custId = getLoginUser().getUser().getCustId();
    		boolean flag = userDcPwdManager.getDCAuth(custId);
    		if (flag) {
    			mav.addObject("haveDcAuth", "1");// 1表示有吧
    		}
    		// end
            
        }

        DecimalFormat f = new DecimalFormat("0.00");
        String payCustId = loginUser==null?null:loginUser.getUser().getCustId();
       
        mav.addObject(GOPAY_ORDER_ID, order.getGopayOrderId());
        mav.addObject("payWayBean", payWay);

        // 标记是否充值交易。
        mav.addObject("inc", inchargeFlag);
        mav.addObject("incUrl", CashierConfig.get(CashierConfig.CASHIER_INCHARGE_REDIRECT_INDEX)+"?acct="+order.getMainRecvAcct());
//        mav.addObject("hideIndivBank", hideIndivBank);

        /*if(isP2P(order)){
            String p2pLoginEmail = "";
            String custId = cpsGpContractInfoDAO.getByContractNo(order.getRemark1()).getExcluCustId();
            CustPersonInfo person = custPersonInfoQueryManager.get(custId);
            if(StringUtils.equals(person.getRegType(),"02")){
                p2pLoginEmail = person.getCustMob();
            }else{
                p2pLoginEmail = person.getEmail();
            }
            //已登录用户不是当前应当登录的用户，强制退出
            if(loginUser!=null && !StringUtils.equals(loginUser.getUser().getCustId(),custId)){
                mav.setViewName("redirect:/pay/info.shtml?"+GOPAY_ORDER_ID+"="+order.getGopayOrderId());
                SecurityUtils.getSubject().logout();
                return mav;
            }
            mav.addObject("p2pLoginEmail", p2pLoginEmail);
        }*/
        OrderInfo orderInfo = getOrderInfo(order.getGopayOrderId());
        mav.addObject("order", orderInfo);
        mav.addObject("pounds", getViewPoundageRes(order));
        if(payCustId!=null){
        	String userType = loginUser.getUser().getUserType();
        	String custName = "";
        	 if(UserType.Person.value.equals(userType)){
         		CustPersonInfo payCust = custPersonInfoQueryManager.get(payCustId);
         		custName = payCust.getCustName();
         	}else{
         		CustCorpInfo payCust = custCorpInfoService.get(payCustId);
         		custName = payCust.getCorpName();
         	}
        	 
        	/*if(StringUtils.equals(orderInfo.getIntTxnCd(), IntTxnCd._00200.value)){
        		//入金需要去掉国付宝支付的页签
        		if(payWay!=null && payWay.isSupport(PayChannelType.GFB_PAY.value)){
        			PayChannelDtlBean bean = payWay.getPayChannelDtl(PayChannelType.GFB_PAY.value);
        			payWay.getPayChannelList().remove(bean);
        		}
        		
            	//会员账户信息
                AcctMastBean bean = getInMoneyAcctBean(payCustId);
                
                if(bean ==null)
                	throw new WebException(ProcCodeConstants.PROC_CODE_100E3030);
                
                //入金计算手续费
        		PoundageRes p = getPoundageRes(order,getPayChannel());
        		if (null == p.getOrderFeePayer()) {
    	            logger.error("没有配置手续费承担方！no OrderFeePayer!" + p);
    	            throw new WebException(ProcCodeConstants.PROC_CODE_100E5051);
    	        }
        		orderInfo.setFeeAmt(f.format(p.getOrderRealFeeAmt()));
        		orderInfo.setFeePayer(p.getOrderFeePayer().value);
                orderInfo.setOrderAmt(f.format(p.getTotalAmt()));
            	//可用余额
            	BigDecimal avaAmt = new BigDecimal(bean.getAvaAmt());
            	mav.addObject("gopayAcctId", bean.getAcctId());
            	mav.addObject("avaAmt", f.format(avaAmt));
            	mav.addObject("custName", custName);

            	int avaFlag = 0;
            	//付款金额
            	BigDecimal payAmt = new BigDecimal(orderInfo.getOrderAmt());
            	if(avaAmt.compareTo(new BigDecimal(0))==0){
            		avaFlag = 3;
            	}else if(avaAmt.compareTo(payAmt)>-1){
            		avaFlag = 1;
            	}else{
            		avaFlag = 2;
            		//差额
            		BigDecimal shortfallPayAmt = payAmt.subtract(avaAmt);
            		mav.addObject("shortfallPayAmt", f.format(shortfallPayAmt));
            	}
            	mav.addObject("avaFlag", avaFlag);
            }else*/ 
            if(StringUtils.equals(orderInfo.getIntTxnCd(), IntTxnCd._00100.value) || StringUtils.equals(orderInfo.getIntTxnCd(), IntTxnCd._00400.value)){
                //modify by jiaoshuai 20161123 修改子账户登录时的账户类型为SUBCLOUD
                //List<AcctBean> accts = getAcctBeans(order, payCustId,AcctProd.CLOUD);
                List<AcctBean> accts = getAcctBeans(order, payCustId,AcctProd.SUBCLOUD);
                if(accts!=null && accts.size()>0){
                    //默认显示第一个账户的余额
                    AcctBean firstAcct = accts.get(0);
                    mav.addObject("acctIds", accts);
                    mav.addObject("avaAmt", f.format(firstAcct.getAmout()));
                    mav.addObject("avaAmt2",firstAcct.getAmout());
                    mav.addObject("custName", custName);
                    mav.addObject("gopayAcctId",firstAcct.getAcctId());
                }
                //取已绑定的快捷银行卡
                mav.addObject("expressCardList",getExpressCardList());
            }
           /* else if(StringUtils.equals(orderInfo.getIntTxnCd(), IntTxnCd._01300.value) || StringUtils.equals(orderInfo.getIntTxnCd(), IntTxnCd._01302.value)){
                List<AcctBean> accts = getP2PAcctBeans(order);
                if(accts!=null && accts.size()>0){
                    //默认显示第一个账户的余额
                    AcctBean firstAcct = accts.get(0);
                    mav.addObject("acctIds", accts);
                    mav.addObject("avaAmt", f.format(firstAcct.getAmout()));
                    mav.addObject("custName", custName);
                }
            }*/
        }
        
      
        
        

        mav.addObject("formhash", setFormHashValue(request,order.getGopayOrderId()));// 防止hack
        //错误提示
        mav.addObject(FIELD_ERR_MSG,request.getSession().getAttribute(FIELD_ERR_MSG));
        request.getSession().removeAttribute(FIELD_ERR_MSG);
        //动态口令卡的提示
        mav.addObject("dcErrMesg", request.getSession().getAttribute("dcErrMesg"));
        request.getSession().removeAttribute("dcErrMesg");
        String loginEmail = getLoginEmail();
        mav.addObject("loginEmail", loginEmail);
        mav.addObject("cashier_url", CASHIER_URL);
        mav.addObject("cas_server_url", CAS_URL);
        mav.addObject("clientIp", RequestUtils.getRemoteRealIpAddr(request));
        mav.addObject("portal_url", PORTAL_URL);
        mav.addObject("sessionId",request.getSession().getId());
        mav.addObject("enable_fingerinfo",ENABLE_FINGERINFO);
        //登录错误返回
        int authErrorCount = getRequest().getSession().getAttribute("authErrorCount") == null ? 0: Integer.parseInt((String)getRequest().getSession().getAttribute("authErrorCount"));
        String casErrFlag = request.getParameter("casErrFlag");
        //<!--0 正常 1 常规校验错误  2 未审核通过 3 外部风控拒绝-->
        if(StringUtils.isNotBlank(request.getParameter("casErrMsg"))){
        	mav.addObject("casCustUserType", request.getParameter("casCustUserType"));
        	mav.addObject("casErrMsg", request.getParameter("casErrMsg"));
        	mav.addObject("casErrFlag",casErrFlag);
            authErrorCount = authErrorCount +1;
            getRequest().getSession().setAttribute("authErrorCount",authErrorCount+"");
            //快捷支付 获取登录密码错误次数--2次及以上显示验证码
            if(authErrorCount>=2){
                mav.addObject("authDisplay","1");
            }
            ch = "06";
        }else{
            getRequest().getSession().removeAttribute("authErrorCount");
        }
        mav.setViewName(getViewName(order.getGopayIntTxnCd()));
        mav.addObject("orderKey",getOrderKey(order.getGopayOrderId()));
        mav.addObject("ch", ch);
        return mav;
    }
    
    private String getCloudAcctId(CpsGenMainOrder order) throws WebException {
    	/** 收款类 */
		if (IntTxnCd._00100.value.equals(order.getGopayIntTxnCd())) return order.getRemark1();
		else if (IntTxnCd._00500.value.equals(order.getGopayIntTxnCd())) return order.getRemark1();

		/** 付款类 */
		logger.error("根据内部交易码获取acctId错误！" + order);
		throw new WebException(ProcCodeConstants.PROC_CODE_100E7006);
	}

	/**
     * 
     * @param ch
     * @return
     * @throws WebException
     */
    @RequestMapping("/sec/pay/cloud/info.shtml")
    public ModelAndView secPayInfo(String ch) throws WebException{
    	ModelAndView mav = new ModelAndView();
    	String newUrl = "/pay/cloud/info.shtml";
    	try {
    		 LoginUser loginUser = getLoginUser();
    		 String gopayUser = getGopayUser();
             String orderId = getRequest().getParameter("orderId");
    		 if(StringUtils.isNotBlank(gopayUser) && loginUser!=null){
                CpsGenMainOrder order = getMainOrder(orderId, true);
                String loginEmail = getLoginEmail();
                Decrypt de = new Decrypt("_gopay_user");
                String user =  de.decrypt(gopayUser);
                mav.addObject("ch", ch);
                mav.addObject("loginEmail", loginEmail);
                mav.addObject("orderId",orderId);
                mav.addObject("orderKey",getOrderKey(orderId));
                if((!StringUtils.equals(user, loginEmail) || user==null) && StringUtils.equals(order.getGopayIntTxnCd(), IntTxnCd._00200.value) ){
                    SecurityUtils.getSubject().logout();
                    mav.setViewName("redirect:"+newUrl);
                    return mav;
                }
            }
            if(loginUser != null){
                //补全用户信息
                CustPersonInfo  custInfo =  custPersonInfoQueryManager.get(loginUser.getUser().getCustId());
                if(custInfo != null){
                    if(StringUtils.equals(custInfo.getCustStat(), CustPersonInfoConstants.CUST_STAT_NORMAL) && StringUtils.isBlank(custInfo.getPayPwd())){
                        OrderInfo orderInfo = getOrderInfo(getRequest().getParameter("orderId"));
                        mav.addObject("order",orderInfo);
                        mav.addObject("custId",loginUser.getUser().getCustId());
                        mav.addObject("orderId",getRequest().getParameter("orderId"));

                        mav.setViewName("00100/content/express/completeInfo");
                        mav.addObject("profession", dicCustProfessionQueryManager.getAll());//职业
                        mav.addObject("questionList", PayPwdQuestionsInfo.getNewQuestionList());//问题
                        mav.addObject("type","2");
                        return mav;
                    }
                }
            }
    		mav.setViewName("forward:"+newUrl);
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
    	return mav;
    }
    
    
    
    @RequestMapping("/sec/pay/cloud/getAvaAmt.shtml")
    @ResponseBody
    public String getAvaAmt(String acctId) throws WebException{
    	if(StringUtils.isBlank(acctId))
    		return "";
    	
    	AcctMastBean bean = acctTransService.getAccount(acctId);
    	if(bean!=null){
    		JSONObject json = new JSONObject();
    		json.accumulate("avaAmt", new DecimalFormat("0.00").format(new BigDecimal(bean.getAvaAmt())));
    		return json.toString();
    	}
    	return "";
    }
    
    private ModelAndView ipCheckDecison(PayInfoCommand command, CpsGenMainOrder order)
            throws WebException {
        String ipCheckDecison = command.getIpCheckDecison();
        
        // 这种情况直接返回null，跳过反钓鱼处理。
        if (!YnFlag.y.code.equals(ipCheckDecison) && !YnFlag.n.code.equals(ipCheckDecison)) return null;
        
        RcsAntiPhishViolateLog log = rcsAntiPhishingViolateLogManager.getByTransDtlSq(order.getTransDtlSq());
        if (null == log) {
            logger.error("反钓鱼日志不存在！RcsAntiPhishViolateLog not exist!" + command);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);
        }
        if (YnFlag.n.code.equals(ipCheckDecison)) {// 反钓鱼-用户选择终止支付
            log.setUserDicision(UserDicision.STOP.code);
            rcsAntiPhishingViolateLogManager.update(log);
            return new ModelAndView("common/close");
        }else if (YnFlag.y.code.equals(ipCheckDecison)) {// 反钓鱼-用户选择继续支付
            log.setUserDicision(UserDicision.CONTINUE.code);
        }
        return null;
    }

    private ModelAndView directBankPayPage(PayInfoCommand command) throws WebException {
        logger.error("直连银行支付 BankRequestController.directBankPayPage " + command);
        // 重新查询订单，状态为最新的
        CpsGenMainOrder order = getMainOrder(getOrderId(), true);
        String userType = "";
        PayChannel payChannel = null;
        if (PayChannel._01.value.equals(order.getPayChannel())) {
            userType = "1";
            payChannel = PayChannel._01;
        }
        else if (PayChannel._51.value.equals(order.getPayChannel())) {
            userType = "2";
            payChannel = PayChannel._51;
        }
        else {
            logger.error("错误的付款通道类型！wrong PayChannel!" + order);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5006);
        }
        ModelAndView mav = new ModelAndView("pay/bankPayForBis");
        OrderInfo orderInfo = getOrderInfo(order.getGopayOrderId());
        mav.addObject("orderId", order.getGopayOrderId());
        mav.addObject("amount", order.getTotalOrderAmt());
        mav.addObject("orderDate", DateUtils.format(order.getGopayTxnTm()));
        mav.addObject("userType", userType);
        mav.addObject("bank", order.getOutStlmId());
        mav.addObject("order", orderInfo);
        mav.addObject("bisUrl", CashierConfig.get(CashierConfig.BIS_URL));
        mav.addObject("bankBusProd", BisBankBusinessProdConvertUtil.getBisBankBusinessProd(payChannel).value);
        //银行客户号
        setB2BBankConfig(mav,PayChannel.get(order.getPayChannel()),order.getOutStlmId());
        return mav;
    }

    private void updateDirectBankPayOrder(PayInfoCommand command, CpsGenMainOrder order) throws WebException {
        // 调用cps更新订单状态为:出款清算单位处理中
        Map<MainOrderField, String> values = new HashMap<MainOrderField, String>();
        PayChannel payChannel = null;
        if (PayChannel._01.value.equals(order.getPayChannel())) {
            payChannel = PayChannel._01;
        }
        else if (PayChannel._51.value.equals(order.getPayChannel())) {
            payChannel = PayChannel._51;
        }else {
            logger.error("错误的付款通道类型！wrong PayChannel!" + order);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5006);
        }
        PoundageRes p = getPoundageRes(order,payChannel);
        values.put(MainOrderField.ORDER_DEAL_AMT, p.getOrderDealAmt().toString());
        values.put(MainOrderField.ORDER_REAL_FEE_AMT, p.getOrderRealFeeAmt().toString());
        values.put(MainOrderField.TOTAL_ORDER_AMT, p.getTotalAmt().toString());
        values.put(MainOrderField.TOTAL_ORDER_FEE_AMT, p.getTotalFeeAmt().toString());
        values.put(MainOrderField.TXN_STA_CD, TxnStaCode.TXN_STA_CD_30101.value + "");

        /**远程IP地址 songefengli 20160922**/
        values.put(MainOrderField.REMOTE_IP, RequestUtils.getRemoteRealIpAddr(getRequest()));

        // 如果是收款方承担手续费，且手续费金额大于订单金额，中断交易，防止实际交易金额为负数。
        if (OrderFeePayer.REC_PAYER.equals(p.getOrderFeePayer())) {
            if (1 == p.getTotalFeeAmt().compareTo(order.getMerTxnAmt())) {
                logger.error("手续费金额大于订单金额，中断交易！pay error: feeAmt[" + p.getTotalFeeAmt() + "]>merTxnAmt["
                        + order.getMerTxnAmt() + "]! " + command + ", " + order);
                throw new WebException(ProcCodeConstants.PROC_CODE_100E5055);
            }
        }

        try {
            logger.error("调用cps更新直连银行订单状态.BEGIN.call cps to update DirectBankPay order" + command + ", " + order + ", "
                    + values);
            mainOrderUpdateService.updateMany(order.getGopayOrderId(), values);
            logger.error("调用cps更新直连银行订单状态.END.call cps to update DirectBankPay order" + command + ", " + order);
        } catch (GopayException e) {
            logger.error("调用cps更新直连银行订单状态出错！call cps to update DirectBankPay order error!" + command + ", " + order, e);
            throw new WebException(e.getErrCode());
        }
    }

    private AcctMastBean getInMoneyAcctBean(String custId){
    	List<AcctMastBean>  accts = acctTransService.getAccounts(custId);
    	if(accts!=null && accts.size()>0){
    		for(AcctMastBean bean : accts){
        		if(bean.getProdCode() == AcctProd.BLME){
        			return bean;
        		}
        	}
    	}
    	return null;
    }


    private void validate(PayInfoCommand command, CpsGenMainOrder order, CustCorpInfo cust)
            throws WebException {
        if (null == order) {
            logger.error("订单不存在！order not exist!" + command);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);
        }
        if (null == cust) {
            logger.error("商户不存在！cust not exist!" + command);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5001);
        }
        /*if (!"1".equals(cust.getIsRealNameCertify())) {
            logger.error("商户未通过实名认证！mer IsRealNameCertify != 1!" + order);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E2031);
        }*/
        // 只有挂起状态的订单才能继续支付
        // 如果允许08状态的订单重新发起，由于OUT_STLM_ID有值了，会误判为直连银行
        if (TxnStaCode.TXN_STA_CD_30000.value != (order.getTxnStaCd())) {
            logger.error("订单状态不对！txn_sta_cd wrong!" + order);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5042);
        }
    }

    private PayChannel getPayChannel(){
        LoginUser userInfo = getLoginUser();
        UserType userType = UserType.get(userInfo.getUser().getUserType());
        PayChannel payChannel = null;
        if (UserType.Person.equals(userType)) {
            payChannel = PayChannel._02;
        } else {
            payChannel = PayChannel._52;
        }
        return payChannel;
    }

    private String getViewName(String intTxnCd){
        if(StringUtils.equals(intTxnCd, IntTxnCd._00100.value)){
            return "cloud/00100/index";
        }else{
            return "cloud/pay/payOrder";
        }
    }

    private List<ExpressCardInfo> getExpressCardList(){
        List<EpCardBindInfoVo> cardList = epBankCardService.getBindCardInfoVoByCustId(getLoginUser().getUser().getCustId());
        if(cardList == null || cardList.size() == 0)
            return null;
        List<ExpressCardInfo> cardInfos = new ArrayList<ExpressCardInfo>();
        for(EpCardBindInfoVo info : cardList){
            ExpressCardInfo ec = new ExpressCardInfo();
            ec.setCardId(info.getSq());
            ec.setBankCardNo(info.getBankAcctNum());
            ec.setExMobileNo(info.getBindMobile());
            ec.setExHolder(info.getBankAcctName());
            ec.setExPayBankCode(info.getBankCode());
            ec.setExIdCardNo(info.getCertNo());
            PayChannel cardPaych = StringUtils.equals(info.getCardType(),EpCardBindInfoVo.CARD_TYPE_CREDIT) ? PayChannel._06 :PayChannel._03;
            ec.setExPayChannel(cardPaych.value);
            if(cardPaych == PayChannel._06)
                ec.setExValidDate(info.getCreditCardExpired());
            	//ec.setExValidDate(DateUtils.format(info.getCreditCardExpired(),"MMyy"));
            cardInfos.add(ec);
        }
        return cardInfos;
    }
}
